﻿using System.Collections.Generic;
using System.Linq;
using DomainModel;
using Repository.Abstract;

namespace Repository.NHibernate
{
    public class UserRepository : Repository<User>, IUserRepository
    {
        #region IUserRepository Members

        public User GetUserByLogin(string login)
        {
            return Session.QueryOver<User>().Where(u => u.Login == login).SingleOrDefault();
        }

        public User GetUserByEmail(string email)
        {
            return Session.QueryOver<User>().Where(u => u.Email == email).SingleOrDefault();
        }

        public int GetCountNotApprovedUsers()
        {
            return Session.QueryOver<User>().Where(u => u.Approved == false).RowCount();
        }

        public IEnumerable<User> GetUsersByGroup(Group group, bool approvedOnly = true)
        {
            if (approvedOnly)
                return Session.QueryOver<User>().Where(u => u.Approved && u.Group.Id == group.Id).List();

            return Session.QueryOver<User>().Where(u => u.Group.Id == group.Id).List();
        }

        public IEnumerable<User> GetUsersByRole(Role role, bool approvedOnly = true)
        {
            if (approvedOnly)
                return Session.QueryOver<User>().Where(u => u.Approved && u.Role == role).List();

            return Session.QueryOver<User>().Where(u => u.Role == role).List();
        }

        public IEnumerable<User> GetStudentsWithoutParent()
        {
            List<User> students = GetUsersByRole(Role.Student).ToList();
            List<User> parents = GetUsersByRole(Role.Parent).ToList();

            foreach (User parent in parents)
            {
                students.Remove(parent.Child);
            }
            return students;
        }

        public User GetParent(User child)
        {
            return Session.QueryOver<User>().Where(u => u.Child == child).SingleOrDefault();
        }

        #endregion
    }
}